package com.zetyun.tiger.format.date.compact;

import com.zetyun.rt.meta.annotation.ActionMeta;
import com.zetyun.rt.sdk.action.MapAction;
import com.zetyun.rt.sdk.model.RtEvent;
import com.zetyun.rt.sdk.operator.OperatorContext;
import com.zetyun.tiger.format.date.SpecialDateFormatUtil;

import java.util.Map;
import java.util.Objects;

import static com.zetyun.tiger.format.date.FormatConstant.*;


@ActionMeta(
        id = "tiger.ebus_pb-date-format",
        tags = {"formatter"},
        category = "map",
        name = "EbusPbDateFormat",
        parameterClass = SimpleDateFormatParameter.class,
        status = ActionMeta.Status.PUBLIC,
        description = "EbusPb系统 表统一日期格式"
)
public class EbusPbDateFormatAction extends MapAction {

    private Map<String, String> mapping;

    @Override
    public void init(OperatorContext context) {
        super.init(context);
        SimpleDateFormatParameter parameters = context.getParameters();
        mapping = parameters.toMapping();


    }

    @Override
    public RtEvent apply(RtEvent in) throws Exception {

        // 获取目标主题名称
        String sinTopic = in.getHeader(SINK_TOPIC, String.class);

        // 根据目标主题名称寻找日期字段 O(1)
        String dateField = mapping.get(sinTopic);

        long procTs = System.currentTimeMillis();
        String currentSystemDate = SpecialDateFormatUtil.toYmdHms(procTs);
        in.setField(RT_PROC_TMS, procTs);
        in.setField(RT_PROC_TIME, currentSystemDate);

        Object dataObject = in.getField(dateField);
        if (Objects.nonNull(dataObject) && !dataObject.toString().isEmpty()) {
            Long dataTs = SpecialDateFormatUtil.toEpbTs(dataObject.toString());
            String formatDate = SpecialDateFormatUtil.toYmdHms(dataTs);
            in.setField(RT_EVENT_TMS, dataTs);
            in.setField(RT_EVENT_TIME, formatDate);
            in.setField(RT_EVENT_DATE, SpecialDateFormatUtil.day(formatDate));
//            in.setField(RT_EVENT_HOUR, SpecialDateFormatUtil.hour(formatDate));
//            in.setField(RT_EVENT_MINU, SpecialDateFormatUtil.minute(formatDate));
        } else {
            in.setField(RT_EVENT_TMS, procTs);
            in.setField(RT_EVENT_TIME, currentSystemDate);
            in.setField(RT_EVENT_DATE, SpecialDateFormatUtil.day(currentSystemDate));
//            in.setField(RT_EVENT_HOUR, SpecialDateFormatUtil.hour(currentSystemDate));
//            in.setField(RT_EVENT_MINU, SpecialDateFormatUtil.minute(currentSystemDate));
        }

        in.setField(RT_EVENT_TYPE, in.getField("op_"));
//        in.setField(RT_EVENT_TYPE, in.getField("op_"));
        in.removeField("op_");
        return in;
    }
}
